package com.tg.service.flow.flow;

import com.tg.service.flow.rule.MetaRuleBase;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.List;

public class SpringFlowEngine<Node extends FlowNode> extends FlowEngine<Node> {

    private ConfigurableApplicationContext context;

    public SpringFlowEngine(List<Node> nodes, ConfigurableApplicationContext context) {
        super(nodes);
        this.context = context;
    }

    public static <Node extends FlowNode> SpringFlowEngine<Node> build(
            List<Node> nodes, ConfigurableApplicationContext context) {
        return new SpringFlowEngine<>(nodes, context);
    }

    @Override
    public boolean validateCondition(String condition, Tuple tuple) {
        SpelExpressionParser parser = new SpelExpressionParser();

        Expression expression = parser.parseExpression(condition);

        StandardEvaluationContext ctx = new StandardEvaluationContext();

        ctx.setVariable("tuple", tuple);

        return (Boolean) expression.getValue(ctx);
    }

    @Override
    public boolean validateNode(String key, Tuple tuple) {
        MetaRuleBase bean = (MetaRuleBase) this.context.getBean(key);
        return bean.invoke(tuple);
    }
}
